package com.iot08.api.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.utils.StringUtils;
import com.iot08.api.config.redis.RedisClusterService;
import com.iot08.api.response.WallpaperResp;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.api.utils.ResponseMapUtil;
import com.iot08.api.utils.buckettool.BaseBucketTool;
import com.iot08.api.vo.request.*;
import com.iot08.common.constant.ConstCacheField;
import com.iot08.common.constant.ConstKafka;
import com.iot08.common.entity.app.UserGoldCoin;
import com.iot08.common.entity.app.UserWallpaper;
import com.iot08.common.entity.app.VipMember;
import com.iot08.common.entity.app.Wallpaper;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cwj
 * @description
 * @date 2025/3/10 17:37
 **/
@Slf4j
@Service
public class WallpaperService extends BaseService<Wallpaper> {

    @Resource
    private VipMemberService vipMemberService;

    @Resource
    private UserWallpaperService userWallpaperService;

    @Resource
    private RedisClusterService redisClusterService;

    @Resource
    private KafkaService kafkaService;

    @Resource
    private BaseBucketTool baseBucketTool;

    @Resource
    private ScreensaverService screensaverService;

    @Resource
    private UserGoldCoinService userGoldCoinService;

    @Resource
    private GoldCoinBuyerOrderService goldCoinBuyerOrderService;

    /**
     * @description 查询壁纸信息
     * @author cwj
     * @param [vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/10 18:09
     **/
    public ResponseMap queryWallpaper(WallpaperQueryReqVo vo){
        List<WallpaperResp> userWallpaperList = null;
        //查询用户已经购买的壁纸信息
        userWallpaperList = queryUserBuyerWallpaper(vo, userWallpaperList);
        //查询用户可以免费使用的图片
        List<WallpaperResp> freeWallpapers = queryFreeUserWallpaper(vo.getOpenid(),vo.getFreeType());
        //查询非免费的热点壁纸，排除免费的
        List<WallpaperResp> hotspotWallpapers = queryHotspotWallpaper();
        //查询不免费的指定类型的壁纸信息
        JSONObject categoryWallpaper = queryWallPaperByCategory(vo);
        ResponseMap res = ResponseMap.success();
        res.put("userWallpapers",userWallpaperList);
        res.put("freeWallpapers",freeWallpapers);
        res.put("hotspotWallpapers",hotspotWallpapers);
        res.put("categoryWallpaper",categoryWallpaper);
        return res;
    }


    /**
     * @description 查询自己购买的
     * @author cwj
     * @param [vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/12 16:14
     **/
    public ResponseMap queryUserWallpaper(WallpaperQueryReqVo vo){
        List<WallpaperResp> userWallpaperList = null;
        long total = 0;
        List<UserWallpaper> userWallpapers = userWallpaperService.queryUserWallpaperByOpenIdOrderDesc(vo.getOpenid());
        if(!CollectionUtils.isEmpty(userWallpapers)) {
            List<ObjectId> ids = userWallpapers.stream().map(UserWallpaper::getWid).filter(ObjectUtils::isNotEmpty).map(ObjectId::new).collect(Collectors.toList());
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").in(ids));
            total = this.count(query);
            userWallpaperList = mongoTemplate.find(query.skip((long) vo.getPage() *vo.getNum()).limit(vo.getNum()),WallpaperResp.class,"wallpaper");
        }
        //拼接壁纸的URL
        assembleWallpaperUrl(userWallpaperList,baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH);
        ResponseMap res = ResponseMap.success();
        res.put("total",total);
        res.put("userWallpapers",userWallpaperList);
        return res;
    }




    /**
     * @description 查询免费壁纸信息
     * @author cwj
     * @param [vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/12 16:02
     **/
    public ResponseMap queryFreeWallpaper(WallpaperQueryReqVo vo){
        //查询用户是否为Vip
        VipMember vipMember = vipMemberService.queryVipMemberByOpenid(vo.getOpenid());
        Query query = createQueryObject(vipMember,vo.getFreeType());
        long total = this.count(query);
        List<WallpaperResp> freeWallpapers = mongoTemplate.find(query.with(Sort.by(Sort.Order.desc("createTime")))
                .skip((long) vo.getPage() *vo.getNum()).limit(vo.getNum()), WallpaperResp.class,"wallpaper");
        //拼接壁纸的URL
        assembleWallpaperUrl(freeWallpapers,baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH);
        ResponseMap res = ResponseMap.success();
        res.put("total",total);
        res.put("freeWallpapers",freeWallpapers);
        return res;
    }


    /**
     * @description
     * @author cwj
     * @param [vipMember]
     * @return org.springframework.data.mongodb.core.query.Query
     * @date @time 2025/3/12 16:09
     **/
    private Query createQueryObject(VipMember vipMember,Integer freeType) {
        Query query = new Query();
        if(ObjectUtils.isNotEmpty(vipMember)) {
            if(ObjectUtils.isEmpty(freeType) || Integer.valueOf(2).equals(freeType)) {
                query.addCriteria(new Criteria().orOperator(Criteria.where("isFree").is(1),
                        new Criteria().andOperator(
                                Criteria.where("isFree").ne(1),
                                Criteria.where("isVipFree").is(1),
                                Criteria.where("vipFreeType").regex(vipMember.getType().toString())
                        )));
            } else if(Integer.valueOf(1).equals(freeType)) {
                query.addCriteria(new Criteria().andOperator(
                                //Criteria.where("isFree").ne(1),
                                Criteria.where("isVipFree").is(1),
                                Criteria.where("vipFreeType").regex(vipMember.getType().toString())
                        ));
            } else if(Integer.valueOf(0).equals(freeType)) {
                query.addCriteria(Criteria.where("isFree").is(1));
            }
        } else {
            query.addCriteria(Criteria.where("isFree").is(1));
        }
        return query;
    }


    /**
     * @description 根据指定分类查询壁纸信息
     * @author cwj
     * @param [vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/12 15:33
     **/
    public ResponseMap queryWallpaperByCid(WallpaperQueryReqVo vo){
        Query query = createQueryObject(vo);
        long total = this.count(query);
        List<WallpaperResp> wallpaperResps = mongoTemplate.find(query.with(Sort.by(Sort.Order.desc("createTime")))
                .skip((long) vo.getPage() *vo.getNum()).limit(vo.getNum()),WallpaperResp.class,"wallpaper");
        //拼接壁纸的URL
        assembleWallpaperUrl(wallpaperResps,baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH);
        ResponseMap res = ResponseMap.success();
        res.put("total", total);
        res.put("categoryWallpapers", wallpaperResps);
        return res;
    }

    /**
     * @description 拼接壁纸的url
     * @author cwj
     * @param [wallpaperResps,path]
     * @return void
     * @date @time 2025/3/13 9:09
     **/
    public static void assembleWallpaperUrl(List<WallpaperResp> wallpaperResps,String path) {
        if(!CollectionUtils.isEmpty(wallpaperResps)) {
            for (WallpaperResp wallpaperResp : wallpaperResps) {
                wallpaperResp.setImageUrl(path+wallpaperResp.getImageUrl());
            }
        }
    }

    /**
     * @description 创建分页查询Query对象
     * @author cwj
     * @param [vo]
     * @return org.springframework.data.mongodb.core.query.Query
     * @date @time 2025/3/12 15:32
     **/
    private Query createQueryObject(WallpaperQueryReqVo vo) {
        Query query = new Query();
        if(ObjectUtils.isEmpty(vo.getPage())) {
            vo.setPage(0);
        }
        if(ObjectUtils.isEmpty(vo.getNum())){
            vo.setNum(20);
        }
        if(StringUtils.isEmpty(vo.getCid())){
            vo.setCName("经典");
            query.addCriteria(Criteria.where("categoryName").is(vo.getCName()));
        } else {
            query.addCriteria(Criteria.where("cid").is(vo.getCid()));
        }
        return query;
    }

    /**
     * @description 查询用户已经购买的皮质信息
     * @author cwj
     * @param [vo, userWallpaperList]
     * @return java.util.List<com.iot08.api.response.WallpaperResp>
     * @date @time 2025/3/12 14:59
     **/
    public List<WallpaperResp> queryUserBuyerWallpaper(WallpaperQueryReqVo vo, List<WallpaperResp> userWallpaperList) {
        List<UserWallpaper> userWallpapers = userWallpaperService.queryUserWallpaperByOpenId(vo.getOpenid());
        if(!CollectionUtils.isEmpty(userWallpapers)) {
            List<ObjectId> ids = userWallpapers.stream().map(UserWallpaper::getWid).filter(ObjectUtils::isNotEmpty).map(ObjectId::new).collect(Collectors.toList());
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").in(ids));
            userWallpaperList = mongoTemplate.find(query,WallpaperResp.class,"wallpaper");
        }
        //拼接壁纸的URL
        assembleWallpaperUrl(userWallpaperList,baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH);
        return userWallpaperList;
    }


    /**
     * @description 查询用户能免费使用的壁纸
     * @author cwj
     * @param [openId]
     * @return java.util.List<com.iot08.common.entity.app.Wallpaper>
     * @date @time 2025/3/11 18:12
     **/
    public List<WallpaperResp> queryFreeUserWallpaper(String openId,Integer freeType){
        //查询用户是否为Vip
        VipMember vipMember = vipMemberService.queryVipMemberByOpenid(openId);
        Query query = createQueryObject(vipMember,freeType);
        List<WallpaperResp> wallpaperResps = mongoTemplate.find(query, WallpaperResp.class,"wallpaper");
        //拼接壁纸的URL
        assembleWallpaperUrl(wallpaperResps,baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH);
        return wallpaperResps;
    }
    

    /**
     * @description 查询非免费的热点壁纸
     * @author cwj
     * @param []
     * @return java.util.List<com.iot08.common.entity.app.Wallpaper>
     * @date @time 2025/3/12 9:31
     **/
    public List<WallpaperResp> queryHotspotWallpaper(){
        Query query = new Query();
       /* query.addCriteria(new Criteria().andOperator(Criteria.where("isFree").ne(1),
                Criteria.where("isVipFree").ne(1)));*/
        query.addCriteria(Criteria.where("isFree").ne(1).and("isVipFree").ne(1));
        query.with(Sort.by(Sort.Direction.DESC, "usedTimes"));
        query.limit(10);
        List<WallpaperResp> wallpaperResps = mongoTemplate.find(query, WallpaperResp.class,"wallpaper");
        //拼接壁纸的URL
        assembleWallpaperUrl(wallpaperResps,baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH);
        return wallpaperResps;
    }



    /**
     * @description 查询不免费的指定分类的壁纸，未指定则用默认分类去查询
     * @author cwj
     * @param [vo]
     * @return java.util.List<com.iot08.common.entity.app.Wallpaper>
     * @date @time 2025/3/12 9:44
     **/
    public JSONObject queryWallPaperByCategory(WallpaperQueryReqVo vo){
        Query query = createQueryObject(vo);
        long total = this.count(query);
        List<WallpaperResp> wallpaperResps = mongoTemplate.find(query.with(Sort.by(Sort.Order.desc("createTime")))
                .skip((long) vo.getPage() *vo.getNum()).limit(vo.getNum()),WallpaperResp.class,"wallpaper");
        //拼接壁纸的URL
        assembleWallpaperUrl(wallpaperResps,baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total",total);
        jsonObject.put("categoryWallpapers",wallpaperResps);
        return jsonObject;
    }
    
    /**
     * @description 根据分类查询Wallpaper单个对象
     * @author cwj
     * @param [cid]
     * @return com.iot08.common.entity.app.Wallpaper
     * @date @time 2025/3/12 11:30
     **/
    public Wallpaper queryWallPaperByCategoryId(String cid){
        Query query = new Query();
        query.addCriteria(Criteria.where("cid").is(cid)).limit(1);
        return this.findOne(query);
    }


    /**
     * @description 更新壁纸的分类名字
     * @author cwj
     * @param [cid, categoryName]
     * @return void
     * @date @time 2025/3/12 11:34
     **/
    public void updateWallPaperByCategoryId(String cid,String categoryName){
        Query query = new Query();
        query.addCriteria(Criteria.where("cid").is(cid));
        Update update = new Update();
        update.set("categoryName",categoryName);
        update.set("updateTime",new Date());
        //更新多条记录
        mongoTemplate.updateMulti(query,update,getClass());
    }


    /***
     * @description 增加壁纸
     * @author cwj
     * @param [vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/12 13:41
     **/
    public ResponseMap addWallpaper(WallpaperAddEditReqVo vo) {
        Wallpaper wallpaper = new Wallpaper();
        wallpaper.setName(vo.getName());
        wallpaper.setCid(vo.getCid());
        wallpaper.setCategoryName(vo.getCategoryName());
        wallpaper.setIsFree(ObjectUtils.isEmpty(vo.getIsFree())?0:vo.getIsFree());
        wallpaper.setIsVipFree(ObjectUtils.isEmpty(vo.getIsVipFree())?0:vo.getIsVipFree());
        wallpaper.setVipFreeType(vo.getVipFreeType());
        wallpaper.setPrice(vo.getPrice());
        wallpaper.setImageUrl(vo.getImageUrl());
        wallpaper.setResolution(vo.getResolution());
        wallpaper.setFileSize(vo.getFileSize());
        wallpaper.setFileFormat(vo.getFileFormat());
        wallpaper.setDesc(vo.getDesc());
        wallpaper.setUsedTimes(vo.getUsedTimes());
        wallpaper.setCreateTime(new Date());
        wallpaper.setUpdateTime(new Date());
        this.save(wallpaper);
        return ResponseMap.success();
    }


    /**
     * @description 修改壁纸信息
     * @author cwj
     * @param [vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/12 13:42
     **/
    public ResponseMap editWallpaper(WallpaperAddEditReqVo vo) {
        Update update = new Update();
        if(!StringUtils.isEmpty(vo.getName())){
            update.set("name",vo.getName());
        }
        if(!StringUtils.isEmpty(vo.getCid())) {
            update.set("cid",vo.getCid());
        }
        if(!StringUtils.isEmpty(vo.getCategoryName())) {
            update.set("categoryName",vo.getCategoryName());
        }
        if(ObjectUtils.isNotEmpty(vo.getIsFree())) {
            update.set("isFree",vo.getIsFree());
        }
        if(ObjectUtils.isNotEmpty(vo.getIsVipFree())) {
            update.set("isVipFree",vo.getIsVipFree());
        }
        if(!StringUtils.isEmpty(vo.getVipFreeType())){
            update.set("vipFreeType",vo.getVipFreeType());
        }
        if(ObjectUtils.isNotEmpty(vo.getPrice())) {
            update.set("price",vo.getPrice());
        }
        if(!StringUtils.isEmpty(vo.getImageUrl())) {
            update.set("imageUrl",vo.getImageUrl());
        }
        if(!StringUtils.isEmpty(vo.getResolution())) {
            update.set("resolution",vo.getResolution());
        }
        if(!StringUtils.isEmpty(vo.getFileSize())) {
            update.set("fileSize",vo.getFileSize());
        }
        if(!StringUtils.isEmpty(vo.getFileFormat())) {
            update.set("fileFormat",vo.getFileFormat());
        }
        if(!StringUtils.isEmpty(vo.getDesc())) {
            update.set("desc",vo.getDesc());
        }
        if(ObjectUtils.isNotEmpty(vo.getUsedTimes())) {
            update.set("usedTimes",vo.getUsedTimes());
        }
        update.set("updateTime",new Date());
        this.updateById(new ObjectId(vo.getWid()),update);
        return ResponseMap.success();
    }


    /**
     * @description 设置壁纸信息
     * @author cwj
     * @param [imei, vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/12 18:00
     **/
    public ResponseMap settingWallpaper(WallpaperSettingReqVo vo) {
        //检查壁纸是否存在
        Wallpaper wallpaper = this.findById(new ObjectId(vo.getWid()));
        if(ObjectUtils.isEmpty(wallpaper)){
            return ResponseMap.fail("系统中已经不存在该壁纸，请联售后解决问题");
        }
        ResponseMap res =  ResponseMap.success();
        //检查是否有权限使用（是否是免费使用或用户已经购买的）
        if(!checkIsAuthSettingWallpaper(wallpaper.getIsFree(), wallpaper.getIsVipFree(), wallpaper.getVipFreeType(),vo.getOpenid(),vo.getWid())) {
            res = ResponseMap.fail("用户无权限直接设置该壁纸，请用金币购买");
            res.put("isAuth",0);
            return res;
        }
        //检查设备是否在线，不在线不能下发
        String onlineStatus = redisClusterService.hget(vo.getImei(), ConstCacheField.ONLINE_STATUS);
        if (!"1".equals(onlineStatus)) {
            return ResponseMap.fail(ResponseEnum.STATUS5001.getCode(), ResponseEnum.STATUS5001.getMsg());
        }
        vo.setImageUrl(wallpaper.getImageUrl());
        //保存数据，上传文件，删除旧文件
        screensaverService.saveOrUpdateWpScreensaver(vo);
        //发送设置专属屏保的指令
        JSONObject kafkaJson = new JSONObject();
        kafkaJson.put("imageUrl", baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH+wallpaper.getImageUrl());
        kafkaService.emitDeviceDemand(vo.getImei(), ConstKafka.DEV_SCREENSAVER, kafkaJson,vo.getOpenid());
        //更新壁纸的设置记录，更新壁纸的热点信息
        updateWallpaperHotspot(vo.getWid());
        res.put("isAuth",1);
        return res;
    }
    
    
    /**
     * @description 检查用户是否有权限设置该壁纸-
     * @author cwj
     * @param [isFree, isVipFree, vipFreeType, openId, wId]
     * @return boolean
     * @date @time 2025/3/13 11:56
     **/
    public boolean checkIsAuthSettingWallpaper(Integer isFree,Integer isVipFree,String vipFreeType,String openId,String wId){
        VipMember vipMember = vipMemberService.queryVipMemberByOpenid(openId);
        UserWallpaper userWallpaper = userWallpaperService.queryUserWallpaperByOpenIdWallpaperId(openId,wId);
        //检查用户有没有权限设置该壁纸
        //壁纸不免费
        if(Integer.valueOf(0).equals(isFree)) {
            //用户未购买壁纸且用户不是会员
            if(ObjectUtils.isEmpty(userWallpaper) && ObjectUtils.isEmpty(vipMember)) {
                return false;
            } else if(ObjectUtils.isEmpty(userWallpaper) && ObjectUtils.isNotEmpty(vipMember)) {
                //免费总送的会员不能使用会员免费壁纸
                if(Integer.valueOf(1).equals(vipMember.getIsOnTrialVip())){
                    return false;
                }
                String vipType = vipMember.getType().toString();
                //用户未购买壁纸且用户是会员，壁纸对某些会员免费
                if(Integer.valueOf(1).equals(isVipFree)) {
                    //检查免费会员类型是否包含该会员类型
                    return !StringUtils.isEmpty(vipFreeType) && vipFreeType.contains(vipType);
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * @description =
     * @author cwj
     * @param [res]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/13 11:44
     **/
    private ResponseMap settingResponseMap(ResponseMap res) {
        res.put("isAuth",0);
        res.put("msg","用户无权限直接设置该壁纸，请用金币购买");
        return res;
    }


    /**
     * @description 更新壁纸的热点信息
     * @author cwj
     * @param [id]
     * @return void
     * @date @time 2025/3/13 9:50
     **/
    public void updateWallpaperHotspot(String id) {
        //让usedTimes字段值+1
        Update update = new Update().inc("usedTimes", 1);
        this.updateById(new ObjectId(id),update);
    }
    
    
    /**
     * @description 购买壁纸
     * @author cwj
     * @param [wIds, bodyForm]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/13 14:23
     **/
    @Transactional
    public ResponseMap buyWallpaper(WallpaperBuyerReqBodyFormVo bodyForm){
        ResponseMap res = ResponseMap.fail(ResponseEnum.STATUS410.getCode());
        int failReason = 0;
        if(StringUtils.isEmpty(bodyForm.getWid())) {
            ResponseMapUtil.settingFailRes(res, failReason,"参数缺失，未传壁纸的id信息");
        }
        //List<ObjectId> wIdList = wIds.stream().map(ObjectId::new).collect(Collectors.toList());
        //查询壁纸信息
        Wallpaper wallpaper = this.findById(new ObjectId(bodyForm.getWid()));
        //检查选择的壁纸中是否存在已经删除的壁纸
        if(ObjectUtils.isEmpty(wallpaper)) {
            //设置然返回值的状态
            ResponseMapUtil.settingFailRes(res, failReason,"所选壁纸已被清除，请刷新页面后重试");
            return res;
        }
        //检查用户是否已经购买过其中的壁纸
        if(userWallpaperService.checkUserWallpaperByOpenIdWallpaperId(bodyForm.getOpenid(), bodyForm.getWid())) {
            failReason = 2;
            //ResponseMapUtil.settingFailRes(res, isGoldCoinInsufficient,"所选壁纸中，用户已经购买过其中的一些壁纸，请用户去除已经购买的壁纸后重新购买");
            ResponseMapUtil.settingFailRes(res, failReason,"");
            return res;
        }
        //查询有效的会员信息
        VipMember vipMember = vipMemberService.queryVipMemberByOpenid(bodyForm.getOpenid());
        boolean isExistsFreeWallpaper = false;
        //检查壁纸中是否存在免费的壁纸
        if(Integer.valueOf(1).equals(wallpaper.getIsFree()) || (ObjectUtils.isNotEmpty(vipMember) &&
                    Integer.valueOf(1).equals(wallpaper.getIsVipFree()) &&
                    !StringUtils.isEmpty(wallpaper.getVipFreeType()) &&
                    wallpaper.getVipFreeType().contains(vipMember.getType().toString()))) {
                isExistsFreeWallpaper = true;
        }
        if(isExistsFreeWallpaper) {
            failReason = 3;
            ResponseMapUtil.settingFailRes(res, failReason,"");
            //ResponseMapUtil.settingFailRes(res, isGoldCoinInsufficient,"所选壁纸中，有些壁纸是免费的，您无需购买，请您去掉免费壁纸后重新购买");
            return res;
        }
        //计算购买壁纸所需要的金币总数
        Integer costGoldCoinTotal = wallpaper.getPrice();
       /* for (Wallpaper wallpaper : wallpapers) {
            //同一张照片只能买一张，因此不许要乘以数量
            costGoldCoinTotal += wallpaper.getPrice();
        }*/
        //检查用户金币数是否足够
        UserGoldCoin userGoldCoin = userGoldCoinService.queryEffectUserGoldCoinByOpenId(bodyForm.getOpenid());
        if(ObjectUtils.isEmpty(userGoldCoin) || ObjectUtils.isEmpty(userGoldCoin.getGoldCoinTotal()) || costGoldCoinTotal > userGoldCoin.getGoldCoinTotal()) {
            failReason = 1;
            //ResponseMapUtil.settingFailRes(res, isGoldCoinInsufficient,"用户没有购买金币或金币数量不足以支付此次壁纸的购买订单");
            ResponseMapUtil.settingFailRes(res, failReason,"");
            return res;
        }
        List<Wallpaper> wallpapers = new ArrayList<>();
        wallpapers.add(wallpaper);
        //创建购买订单及订单详情
        String orderId = goldCoinBuyerOrderService.createWallpapperGoldCoinBuyerOrder(wallpapers,costGoldCoinTotal,bodyForm.getOpenid(),1,userGoldCoin.getGoldCoinTotal());
        boolean isSaveSuccess = false;
        //创建用户购买的壁纸记录
        if(!StringUtils.isEmpty(orderId)) {
            isSaveSuccess = userWallpaperService.createUserWallpaper(wallpapers,bodyForm.getOpenid(),orderId,1);
        }
        //减少用户金币信息
        if(isSaveSuccess) {
            userGoldCoinService.updateUserGoldCoinNumById(userGoldCoin.getId(),costGoldCoinTotal);
        }
        ResponseMapUtil.settingFailRes(res, failReason,"壁纸购买失败,保存用户壁纸信息时出现异常");
        return isSaveSuccess ? ResponseMap.success():res;
    }


    /**
     * @description 检查用户壁纸是否直接可使用
     * @author cwj
     * @param [vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/21 10:25
     **/
    public ResponseMap checkWallpaper(WallpaperCheckReqVo vo) {
        ResponseMap res = ResponseMap.success();
        int wStatus = 4;
        int goldCoinTotal = 0;
        int realDeductGoldCoin = 0;
        String vipFreeDesc = "";
        UserGoldCoin userGoldCoin = userGoldCoinService.queryEffectUserGoldCoinByOpenId(vo.getOpenid());
        if(!ObjectUtils.isEmpty(userGoldCoin) && !ObjectUtils.isEmpty(userGoldCoin.getGoldCoinTotal())) {
            goldCoinTotal = userGoldCoin.getGoldCoinTotal();
        }
        res.put("goldCoinTotal",goldCoinTotal);
        Wallpaper wallpaper = this.findById(new ObjectId(vo.getWid()));
        realDeductGoldCoin = wallpaper.getPrice();
        //组装免费说名
        vipFreeDesc = assembleFreeDesc(wallpaper.getIsFree(),wallpaper.getIsVipFree(),wallpaper.getVipFreeType(),vipFreeDesc);
        //检查选择的壁纸中是否存在已经删除的壁纸
        if(ObjectUtils.isEmpty(wallpaper)) {
            wStatus = 0;
            res = ResponseMap.fail("您所选择的壁纸已不存在，请更换壁纸");
            res.put("goldCoinTotal",goldCoinTotal);
            realDeductGoldCoin = 0;
            //设置然返回值的状态
            settingResponseData(res, wStatus, realDeductGoldCoin ,vipFreeDesc);
            return res;
        }
        //检查用户是否已经购买过其中的壁纸
        if(userWallpaperService.checkUserWallpaperByOpenIdWallpaperId(vo.getOpenid(), vo.getWid())) {
            wStatus = 2;
            realDeductGoldCoin = 0;
            settingResponseData(res, wStatus,realDeductGoldCoin, vipFreeDesc);
            return res;
        }
        //查询有效的会员信息
        VipMember vipMember = vipMemberService.queryVipMemberByOpenid(vo.getOpenid());
        boolean isExistsFreeWallpaper = false;
        //检查壁纸中是否存在免费的壁纸
        if(Integer.valueOf(1).equals(wallpaper.getIsFree()) || (ObjectUtils.isNotEmpty(vipMember) &&
                Integer.valueOf(1).equals(wallpaper.getIsVipFree()) &&
                !StringUtils.isEmpty(wallpaper.getVipFreeType()) &&
                wallpaper.getVipFreeType().contains(vipMember.getType().toString()))) {
            isExistsFreeWallpaper = true;
        }
        if(isExistsFreeWallpaper) {
            wStatus = 3;
            realDeductGoldCoin = 0;
            settingResponseData(res, wStatus,realDeductGoldCoin, vipFreeDesc);
            return res;
        }
        if(ObjectUtils.isEmpty(userGoldCoin) || ObjectUtils.isEmpty(userGoldCoin.getGoldCoinTotal()) || wallpaper.getPrice() > userGoldCoin.getGoldCoinTotal()) {
            wStatus = 1;
            settingResponseData(res, wStatus,realDeductGoldCoin, vipFreeDesc);
            return res;
        }
        settingResponseData(res, wStatus, realDeductGoldCoin,vipFreeDesc);
        return res;
    }

    /**
     * @description 设置返回数据
     * @author cwj
     * @param [res, wStatus, vipFreeDesc]
     * @return void
     * @date @time 2025/3/22 12:24
     **/
    private void settingResponseData(ResponseMap res, int wStatus,int realDeductGoldCoin, String vipFreeDesc) {
        res.put("wStatus", wStatus);
        res.put("realDeductGoldCoin",realDeductGoldCoin);
        res.put("vipFreeDesc", vipFreeDesc);
    }

    /**
     * @description 组装免费说明
     * @author cwj
     * @param [isFree, isVipFree, vipFreeType, vipFreeDesc]
     * @return java.lang.String
     * @date @time 2025/3/22 12:22
     **/
    private String assembleFreeDesc(Integer isFree,Integer isVipFree,String vipFreeType,String vipFreeDesc) {
        if(Integer.valueOf(1).equals(isFree)) {
            vipFreeDesc = "所有用户免费";
        } else if(Integer.valueOf(1).equals(isVipFree) && !StringUtils.isEmpty(vipFreeType)) {
            if(vipFreeType.contains("1")) {
                vipFreeDesc += "月会员";
            }
            if(vipFreeType.contains("2")) {
                if(StringUtils.isEmpty(vipFreeDesc)) {
                    vipFreeDesc += "年会员";
                } else {
                    vipFreeDesc += "、年会员";
                }
            }
            if(vipFreeType.contains("3")) {
                if(StringUtils.isEmpty(vipFreeDesc)) {
                    vipFreeDesc += "永久会员";
                } else {
                    vipFreeDesc += "、永久会员";
                }
            }
            if(!StringUtils.isEmpty(vipFreeDesc)) {
                vipFreeDesc += "免费";
            }
        } else {
            vipFreeDesc = "不免费";
        }
        return vipFreeDesc;
    }

    /**
     * @description 根据ids查询壁纸信息
     * @author cwj
     * @param [wIdList]
     * @return java.util.List<com.iot08.common.entity.app.Wallpaper>
     * @date @time 2025/3/13 15:07
     **/
    public List<Wallpaper> queryWallpaperByIds(List<ObjectId> wIdList) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").in(wIdList));
        return this.find(query);
    }
}
